#include <audiere.h>
#include "AudioModule.h"
#include "../Model/AudioBook.h"
#include <math.h>

using namespace audiere;
std::string AudioModule::debugOutput() {

	return book.getFile(0) + book.getFile(1) + book.getFile(2) + book.getFile(3);

}


AudioModule::AudioModule(AudioBook & b) {
	device = OpenDevice();
	book = b;
	currentFileIndex = 0;
	if (book.getLength() > 0) openCurrentFile();
	//if (device == 0) throw "CAN'T OPEN DEVICE";
}

AudioModule::AudioModule() {
	//currentFileIndex = 0;
	//device = OpenDevice();
}


void AudioModule::openCurrentFile() {
	sound = OpenSound(device, book.getFile(currentFileIndex).c_str());
	//if (sound == 0) throw "CAN'T OPEN SOUND " + book.getFile(currentFileIndex);
}

void AudioModule::play() {
	sound->setVolume(1.0f);
	sound->play();
}

void AudioModule::stop() {
	sound->stop();
}
 
void AudioModule::setPosition(int pos) {
	sound->setPosition(pos);
}

int AudioModule::getPosition() {
	return sound->getPosition();
}

void AudioModule::setFileIndex(int i) {
	currentFileIndex = i;
	openCurrentFile();
}

int AudioModule::getFileIndex() {
	return currentFileIndex;
}

void AudioModule::nextFile() {
	if (isPlaying()) stop();
	++currentFileIndex;
	openCurrentFile();
	play();	
}

bool AudioModule::isPlaying() {
	return sound -> isPlaying();
}

void AudioModule::adjust(double c) {
	int i = floor(c*book.getLength());
	if (i != currentFileIndex) {
		currentFileIndex = i;
		sound->stop();
		openCurrentFile();
		sound->play();
	}
	
}


std::string AudioModule::getCurrentFileName() {
	return book.getFile(currentFileIndex);
}
